<!-- 车企管理-->
<template>
    <div class="safelist-search-container resource-manage">
        <div class="mb16 flex-sba">
            <a-row class="search-row" :gutter="20">
                <a-col>
                    企业名称:
                    <a-input v-model:value="state.searchData.likeName"
                        style="width: 200px;"
                        placeholder="请输入企业名称"
                        allowClear
                    />
                </a-col>
                <a-col>
                    全部状态:
                    <a-select v-model:value="state.searchData.status"
                        style="width: 200px;"
                        placeholder="请选择状态"
                        allowClear>
                        <a-select-option value="全部状态">全部状态</a-select-option>
                        <a-select-option value="正常">正常</a-select-option>
                        <a-select-option value="停用">停用</a-select-option>
                        <a-select-option value="审核中">审核中</a-select-option>
                    </a-select>
                </a-col>
                <a-col >
                    <a-button type="primary"
                        class="mr8"
                        @click="handleSearch">搜索</a-button>
                    <a-button type="primary"
                        ghost
                        @click="handleEmpty">重置</a-button>
                </a-col>
            </a-row>
            <div>
                <a-button type="primary" danger class="nmc-add-btn-primary"
                  
                    @click="addRole(1)"
                >新增</a-button>
            </div>
        </div>
        <div class="safelist-table-container">
            <a-table :columns="tableProps.columns"
                :data-source="tableProps.dataSource"
                :pagination="tableProps.pagination"
                :scroll="{ y:'calc(100vh - 320px)'}"
  
                :loading="state.loading"
            >

                <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex == 'businessLicense'">
                        <a-image
                            :src="record.businessLicense || '/placeholder.png'"
                            :width="40"
                            :height="40"
                            style="border-radius: 4px;"
                            :fallback="'/placeholder.png'"
                        />
                    </template>
                    <template v-if="column.dataIndex == 'action'">
                        <a style="margin-right: 8px; color: #1890ff;"
                            @click='addRole(3,record)'
                        >查看详情</a>
                        <a style="margin-right: 8px; color: #1890ff;"
                            @click='addRole(2,record)'
                        >编辑</a>
                        <a style="margin-right: 8px; color: #ff4d4f;"
                            @click='getRoleDelete(record)'
                        >删除</a>
                    </template>
                </template>
            </a-table>
        </div>
    </div>
    
    <!-- 编辑弹窗 -->
    <carCompanyEdit 
        ref="carCompanyEditRef"
        @success="handleEditSuccess"
    />
</template>

<script setup lang='jsx'>
import { onMounted, reactive, ref, unref, defineProps, createVNode, defineOptions } from 'vue'
import { bizManufacturerQueryPage, bizManufacturerDelete } from "@/service/nmcApi"
import { useRouter } from 'vue-router'
import { message, Modal } from "ant-design-vue"
import { ExclamationCircleOutlined } from "@ant-design/icons-vue"
import { useMainStore } from "@/store"
import carCompanyEdit from './components/carCompanyEdit.vue'

defineOptions({
    name: 'carCompanyManage'
})

const router = useRouter()
const mainStore = useMainStore()

const carCompanyEditRef = ref(null)

const props = defineProps({
    // orgTreeData: {
    //     default: () => [],
    //     type: Array
    // },
})

// 表格选择配置
const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        console.log('selectedRows: ', selectedRows);
    },
    getCheckboxProps: (record) => ({
        disabled: record.name === 'Disabled User',
        name: record.name,
    }),
};

const tableProps = ref({
    columns: [
        {
            title: '序号',
            dataIndex: 'index',
            width:70,
            customRender: ({text, record, index, column}) =>{
                return (tableProps.value.pagination.current - 1) * tableProps.value.pagination.pageSize + Number(index) + 1;
            }
        },
        {
            title: '车企名称',
            dataIndex: 'name',
        },
        {
            title: '营业执照',
            dataIndex: 'businessLicense',
            width: 80,
        },
        {
            title: '法定代表人',
            dataIndex: 'legalName',
        },
        {
            title: '负责人姓名',
            dataIndex: 'directorName',
        },
        {
            title: '负责人电话',
            dataIndex: 'directorPhone',
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            width: 160,
        },
        {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            width:200
        }
    ],
    dataSource: [], //列表数据
    pagination: {
        current: 1,//当前页数
        pageSize: 10,//每页条数
        total: 0,
        showSizeChanger: true,
        showTotal: (total) => `${total}条`,
        showQuickJumper: true,
        onChange: (current, pageSize) => {
            tableProps.value.pagination.current = current;
            tableProps.value.pagination.pageSize = pageSize;
            getRolePage();
        }
    }
})

const state = reactive({
    //搜索数据
    searchData: {
        likeName: null, //企业名称
        status: null, //状态
    },
    loading: false // 添加加载状态
})

onMounted(async() => {
    getSoure();
    getRolePage();
})

// 基础数据
const getSoure= (type,row)=>{

}

const addRole = (type, record) => {
    // type 1 新增 2 编辑 3 查看详情
    if (type === 1) {
        // 新增车企
        carCompanyEditRef.value.showModal({
            title: '新增车企' , 
            showType: 'add'
        })
    } else if (type === 2) {
        // 编辑车企
        carCompanyEditRef.value.showModal({
            title: '编辑车企',
            ...record,
            showType: 'edit'
        })
    } else if (type === 3) {
        // 查看详情
        carCompanyEditRef.value.showModal({
            title: '查看详情',
            ...record,
            showType: 'view'
        })
    }
}

// 查看详情
const handleViewDetails = (record) => {
    // 这里可以跳转到详情页面或打开详情弹窗
    console.log('查看详情:', record)
    message.info('查看详情功能待实现')
}

// 处理编辑成功
const handleEditSuccess = (data) => {
    message.success('保存成功')
    getRolePage() // 刷新列表
}

//获取列表数据
const getRolePage = () => {
    state.loading = true
    
    let params = {
        pageNo: tableProps.value.pagination.current,
        pageSize: tableProps.value.pagination.pageSize,
        ...state.searchData
    }
    
    
    bizManufacturerQueryPage(params).then(res => {
        if (res && res.status === "000_0000_0000") {
            tableProps.value.dataSource = res.result.list
            tableProps.value.pagination.total = Number(res.result.total)
        } else {
            tableProps.value.dataSource = []
            tableProps.value.pagination.total = 0
            message.warning('暂无数据')
        }
    }).catch(err => {
        console.error('获取车企列表失败:', err)
        tableProps.value.dataSource = []
        tableProps.value.pagination.total = 0
        message.error('获取列表失败，请检查网络连接')
    }).finally(() => {
        state.loading = false
    })

    // 注释掉模拟数据
    // tableProps.value.dataSource = [
    //     {
    //         id: 1,
    //         name: '上海仙途智能科技有限公司',
    //         businessLicense: '/business-license-1.jpg',
    //         legalName: '肖腾',
    //         directorPhone: '18827063498',
    //         directorName: '肖腾'
    //     },
    //     {
    //         id: 2,
    //         name: '上海仙途智能科技有限公司',
    //         businessLicense: '/business-license-2.jpg',
    //         legalName: '周贺',
    //         directorPhone: '18827063498',
    //         directorName: '周贺'
    //     },
    //     {
    //         id: 3,
    //         name: '上海仙途智能科技有限公司',
    //         businessLicense: '/business-license-3.jpg',
    //         legalName: '韩旭',
    //         directorPhone: '18827063498',
    //         directorName: '韩旭'
    //     },
    //     {
    //         id: 4,
    //         name: '上海仙途智能科技有限公司',
    //         businessLicense: '/business-license-4.jpg',
    //         legalName: '李明',
    //         directorPhone: '18827063498',
    //         directorName: '李明'
    //     },
    //     {
    //         id: 5,
    //         name: '上海仙途智能科技有限公司',
    //         businessLicense: '/business-license-5.jpg',
    //         legalName: '王强',
    //         directorPhone: '18827063498',
    //         directorName: '王强'
    //     },
    //     {
    //         id: 6,
    //         name: '上海仙途智能科技有限公司',
    //         businessLicense: '/business-license-6.jpg',
    //         legalName: '张伟',
    //         directorPhone: '18827063498',
    //         directorName: '张伟'
    //     },
    //     {
    //         id: 7,
    //         name: '上海仙途智能科技有限公司',
    //         businessLicense: '/business-license-7.jpg',
    //         legalName: '刘芳',
    //         directorPhone: '18827063498',
    //         directorName: '刘芳'
    //     },
    //     {
    //         id: 8,
    //         name: '上海仙途智能科技有限公司',
    //         businessLicense: '/business-license-8.jpg',
    //         legalName: '陈静',
    //         directorPhone: '18827063498',
    //         directorName: '陈静'
    //     },
    //     {
    //         id: 9,
    //         name: '上海仙途智能科技有限公司',
    //         businessLicense: '/business-license-9.jpg',
    //         legalName: '赵敏',
    //         directorPhone: '18827063498',
    //         directorName: '赵敏'
    //     }
    // ]
    // tableProps.value.pagination.total = 156
}
//搜索
const handleSearch = () => {
    tableProps.value.pagination.current = 1
    getRolePage()
}
//重置
const handleEmpty = () => {
    state.searchData = {
        likeName: null, //企业类型
        status: null, //状态
    }
    tableProps.value.pagination.current = 1
    tableProps.value.pagination.pageSize = 10
    getRolePage()
}

// 点击 删除
const getRoleDelete = (record) => {
    Modal.confirm({
        title: '提示',
        icon: createVNode(ExclamationCircleOutlined),
        content: `您是否要删除"${record.name}"？`,
        okText: '确认',
        cancelText: '取消',
        onOk () {
            return new Promise((resolve, reject) => {
                bizManufacturerDelete({ id: record.id }).then(res => {
                    if (res && res.status === "000_0000_0000") {
                        message.success('删除成功')
                        getRolePage()
                        resolve()
                    } else {
                        message.error(res.message || '删除失败')
                        reject()
                    }
                }).catch(err => {
                    console.error('删除失败:', err)
                    message.error('删除失败')
                    reject()
                })
            })
        },
    });
}

// // 批量删除
// const handleBatchDelete = () => {
//     if (!rowSelection.selectedRowKeys || rowSelection.selectedRowKeys.length === 0) {
//         message.warning('请选择要删除的车企')
//         return
//     }
    
//     Modal.confirm({
//         title: '批量删除确认',
//         icon: createVNode(ExclamationCircleOutlined),
//         content: `您确定要删除选中的 ${rowSelection.selectedRowKeys.length} 个车企吗？`,
//         okText: '确认',
//         cancelText: '取消',
//         onOk () {
//             return new Promise((resolve, reject) => {
//                 // 这里可以实现批量删除逻辑
//                 message.success(`成功删除 ${rowSelection.selectedRowKeys.length} 个车企`)
//                 rowSelection.selectedRowKeys = []
//                 rowSelection.selectedRows = []
//                 getRolePage()
//                 resolve()
//             })
//         },
//     });
// }

// // 导出数据
// const handleExport = () => {
//     if (tableProps.value.dataSource.length === 0) {
//         message.warning('暂无数据可导出')
//         return
//     }
    
//     // 这里可以实现导出逻辑
//     message.success('导出功能开发中，请联系开发人员')
// }

</script>
<style lang="less" scoped>
.resource-manage {
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}
.safelist-table-container {
    height: calc(100% - 48px);
    overflow: hidden;
}

.data-statistics {
    .stat-item {
        text-align: center;
        
        .stat-number {
            font-size: 24px;
            font-weight: bold;
            color: #1890ff;
            margin-bottom: 8px;
        }
        
        .stat-label {
            font-size: 14px;
            color: #666;
        }
    }
}
</style>
